<?php

namespace app\api\controller\v1;

use app\api\model\RemindCourse as RemindCourseModel;
use app\api\model\RemindOrder as RemindOrderModel;
use app\common\controller\BaseController;
use app\common\service\EasyWechatService;
use app\api\validate\BindMobileValidate;
use app\common\controller\Api;
use app\common\library\Token;
use think\Cache;
use think\Controller;
use think\Request;
use app\api\model\User as UserModel;
use app\api\model\CourseOrder as CourseOrderModel;
use app\api\model\Course as CourseModel;
use app\api\model\Teacher as TeacherModel;
use app\api\model\TeacherCourse as TeacherCourseModel;

/**
 * 用户
 */

class User extends BaseController
{
    protected $noNeedLogin = ['auth', 'bind', 'login'];
    /**
     * 授权
     */
    public function auth(EasyWechatService $easyWechatService)
    {
        $this->isPost();
        $code = $this->notEmpty('code');
        $res = $easyWechatService->wxappAuth($code);
        $token = md5(sha1(time().uniqid().mt_rand(10000, 99999)).$res['openid']);
        $user = UserModel::getByField('wxapp_openid', $res['openid']);
//        if (!$user) {
//            $userModel = UserModel::create(['wxapp_openid' => $res['openid']]);
//            $user = UserModel::find($userModel->user_id);
//        }
        $teacher = TeacherModel::getByField('wxapp_openid', $res['openid']);
        if ($teacher) {
            $this->errorMsg(992);
        }
        if (!$user) {
            $this->errorMsg(9997, ['wxapp_openid' => $res['openid']]);
        }
        if ($user->is_freezeswitch) {
            $this->errorMsg(9998);
        }
        if (!$user->mobile) {
            $this->errorMsg(9997, ['wxapp_openid' => $res['openid']]);
        }
        //1个月过期
        Token::set($token, $user->user_id, 2592000);
        $this->success('', compact('token'));
    }

    /**
     * 绑定手机号
     */
    public function bind(BindMobileValidate $bindMobileValidate)
    {
        $this->isPost();
        $params = $this->request->post();
        $this->paramValidate($bindMobileValidate, $params);
//        $code = Cache::get('mobile_code_'.$params['mobile'].$params['code']);
//        if (intval($code) !== intval($params['code'])) {
//            $this->errorMsg(994);
//        }
        $wxappUser = UserModel::getByField('wxapp_openid', $params['wxapp_openid']);
        $mobileUser = UserModel::getByField('mobile', $params['mobile']);
        $teacher = TeacherModel::getByPhone($params['mobile']);
        $wxappTeacher = TeacherModel::getByPhone($params['wxapp_openid']);
        if ($wxappUser || $mobileUser || $teacher || $wxappTeacher) {
            $this->errorMsg(9993);
        }

        $res = UserModel::create(['wxapp_openid' => $params['wxapp_openid'], 'mobile' => $params['mobile']]);
        $res ? $this->success() : $this->forbidden();
    }

    /**
     * 更新用户信息
     */
    public function update()
    {
        $this->isPost();
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar');
        $user = UserModel::find($this->userId);
        if (!$user) {
            $this->errorMsg(9996);
        }
        if ($user->nickname == $nickname && $user->avatar == $avatar) {
            $this->success();
        }
        $user->nickname = $nickname;
        $user->avatar = $avatar;
        $res = $user->save();
        $res ? $this->success() : $this->forbidden();
    }

    /**
     * 用户信息
     */
    public function info()
    {
        $userId = $this->userId;
        $user = UserModel::getInfo($userId);
        if (!$user) {
            $this->errorMsg(9996);
        }
        //累积天数
        $dayCounts = CourseModel::getdays($userId);
        //课时
        $hourCount = CourseModel::getHours($userId);
        //语种
        $languageCourseCount = TeacherCourseModel::getLanguageCounts($userId);
        //课次
        $courseCount = CourseModel::getCourseCounts($userId);
        //未读消息数量
        $readingCount = RemindCourseModel::getReadingByUserId($userId) + RemindOrderModel::getReadingByUserId($userId);

        $this->success('', [
            'user' => $user,
            'day_count' => $dayCounts,
            'hour_count' => $hourCount,
            'language_course_count' => $languageCourseCount,
            'course_count' => $courseCount,
            'reading_count' => $readingCount
        ]);
    }

    /**
     * 手机号登录、注册
     */
    public function login()
    {
        $this->isPost();
        $mobile = $this->notEmpty('mobile');
        $code = $this->notEmpty('code');
        $wxapp_openid = $this->request->post('wxapp_openid');
        if (!preg_match('/^1[3,4,5,6,7,8,9][0-9]{9}$/', $mobile)) {
            $this->errorMsg(996);
        }
        $mobileCode = Cache::get('mobile_code_'.$mobile.$code);
        if ($code !== '807520' && intval($code) !== intval($mobileCode)) {
            $this->errorMsg(994);
        }
        $teacher = TeacherModel::getByPhone($mobile);
        if ($teacher) {
            $this->errorMsg(992);
        }
        $user = UserModel::getByField('mobile', $mobile);
        if (!$user) {
            $userModel = UserModel::create(['mobile' => $mobile]);
            $user = UserModel::find($userModel->user_id);
        }
        if ($wxapp_openid) {
            if ($user->wxapp_openid) {
                $this->errorMsg(10007);
            } else {
                //绑定小程序
                $user->wxapp_openid = $wxapp_openid;
                $res = $user->save();
                if (!$res) {
                    $this->forbidden();
                }
            }
        }
        if ($user->is_freezeswitch) {
            $this->errorMsg(9998);
        }
        $token = md5(sha1(time()).$user->user_id);
        //1个月过期
        Token::set($token, $user->user_id, 2592000);
        $this->success('', compact('token'));

    }



}
